<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>商品管理</el-breadcrumb-item>
        <el-breadcrumb-item>商品参数</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
        <el-alert
            title="注意: 只能选择第三级分类设置相关参数"
            type="warning"
            show-icon
            :closable="false">
        </el-alert>
        <el-row style="margin: 15px 0">
            <el-col>
            <span>选择商品分类：</span>
            <el-cascader
                clearable
                v-model="selectedKeys"
                :options="cateList"
                :props="cascaderProps"
                @change="cascaderChange">
            </el-cascader>
            </el-col>
        </el-row>
        <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="动态参数" name="many">
            <el-button type="primary" size="mini" :disabled="isBtnDisabled"
            @click="addDialogVisible = true">添加参数</el-button>
            <el-table
            :data="manyTableData"
            border
            style="width: 100%">
                <el-table-column
                type="expand">
                <template slot-scope="scope">
                    <el-tag v-for="i,index in scope.row.attr_vals" :key="index" 
                    style="margin-left: 20px"
                    closable
                    @close="handleClose(index,scope.row)">
                        {{ i }}
                    </el-tag>
                    <!-- new tag -->
                    <el-input
                    class="input-new-tag"
                    v-if="scope.row.inputVisible"
                    v-model="scope.row.inputValue"
                    ref="saveTagInput"
                    size="small"
                    @keyup.enter.native="handleInputConfirm(scope.row)"
                    @blur="handleInputConfirm(scope.row)"
                    >
                    </el-input>
                    <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                </template>
                </el-table-column>
                <el-table-column
                type="index">
                </el-table-column>
                <el-table-column
                prop="attr_name"
                label="参数名称">
                </el-table-column>
                <el-table-column
                label="操作">
                  <template slot-scope="scope">
                    <el-button size="mini" type="primary" icon="el-icon-edit"
                    @click="showEditDialog(scope.row.attr_id)">编辑</el-button>
                    <el-button size="mini" type="danger" icon="el-icon-delete"
                    @click="deleteParams(scope.row.attr_id)">删除</el-button>
                  </template>
                </el-table-column>
            </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
            <el-button type="primary" size="mini" :disabled="isBtnDisabled"
            @click="addDialogVisible = true">添加属性</el-button>
            <el-table
            :data="onlyTableData"
            border
            style="width: 100%">
                <el-table-column
                type="expand">
                <template slot-scope="scope">
                    <el-tag 
                    v-for="i,index in scope.row.attr_vals" :key="index"
                    style="margin-left: 20px"
                    closable
                    @close="handleClose(index,scope.row)">
                        {{ i }}
                    </el-tag>
                    <el-input
                    class="input-new-tag"
                    v-if="scope.row.inputVisible"
                    v-model="scope.row.inputValue"
                    ref="saveTagInput"
                    size="small"
                    @keyup.enter.native="handleInputConfirm(scope.row)"
                    @blur="handleInputConfirm(scope.row)"
                    >
                    </el-input>
                    <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                </template>
                </el-table-column>
                <el-table-column
                type="index">
                </el-table-column>
                <el-table-column
                prop="attr_name"
                label="属性名称">
                </el-table-column>
                <el-table-column
                label="操作">
                  <template slot-scope="scope">
                    <el-button size="mini" type="primary" icon="el-icon-edit"
                    @click="showEditDialog(scope.row.attr_id)">编辑</el-button>
                    <el-button size="mini" type="danger" icon="el-icon-delete"
                    @click="deleteParams(scope.row.attr_id)">删除</el-button>
                  </template>
                </el-table-column>
            </el-table>
        </el-tab-pane>
        </el-tabs>
    </el-card>
    <el-dialog
    :title="'添加'+diaTitle"
    :visible.sync="addDialogVisible"
    width="50%"
    @close="addDialogClosed">
    <el-form :model="addFrom" ref="addFormRef" label-width="150px" 
    class="demo-ruleForm"
    :rules="addFromRules">
        <el-form-item :label="diaTitle" prop="attr_name">
            <el-input v-model="addFrom.attr_name"></el-input>
        </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
    </span>
    </el-dialog>
    <!-- 修改参数 -->
    <el-dialog
    :title="'修改'+diaTitle"
    :visible.sync="editDialogVisible"
    width="50%"
    @close="editDialogClosed">
    <el-form :model="editFrom" ref="editFormRef" label-width="150px" 
    class="demo-ruleForm"
    :rules="editFromRules">
        <el-form-item :label="diaTitle" prop="attr_name">
            <el-input v-model="editFrom.attr_name"></el-input>
        </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
    </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
    name: 'ParamPage',
    data(){
        return{
            // 商品分类数据
            cateList: [],
            // 级联选择器配置
            cascaderProps: {
                expandTrigger: 'hover',
                value: 'cat_id', // 选中的值
                label: 'cat_name',  // 显示的内容
                children: 'children',  // 嵌套所用的属性
            },
            selectedKeys: [],
            // tabs
            activeName: 'many',
            // 动态 / 静态 数据
            manyTableData: [],
            onlyTableData: [],
            // dialog Add
            addDialogVisible: false,
            addFrom: {
                attr_name: ''
            },
            addFromRules: {
                attr_name: [
                    { required: true, message: '请输入',trigger: 'blur' }
                ]
            },
            // Edit
            editDialogVisible: false,
            editFrom: {},
            editFromRules: {
                attr_name: [
                    { required: true, message: '请输入',trigger: 'blur' }
                ]
            },
        }
    },
    created(){
        this.getCateList()
    },
    methods: {
        async getCateList(){
            const{data:res} = await this.$http.get('categories')
            if(res.meta.status !== 200) return this.$message.error('获取商品分类失败')
            // console.log(res.data)
            this.cateList = res.data
        },
        // 级联选择器改变事件
        cascaderChange(){
            this.getParamsData()
        },
        // tab切换
        handleClick(){
            // console.log(this.activeName)
            this.getParamsData()
        },
        // 获取参数数据
        async getParamsData(){
            if(this.selectedKeys.length !== 3){
                // 选择为非三级菜单时，清空已选择数据
                this.selectedKeys = []
                this.manyTableData = []
                this.onlyTableData = []
                return
            }
            // console.log(this.selectedKeys)
            const{data:res} = await this.$http.get(`categories/${this.cateId}/attributes`,{params:{
                sel: this.activeName
            }})
            if(res.meta.status !== 200){return this.$message.error('获取分类数据失败')}
            else{
                console.log('tabledata',res)
                // 将每一项的 attr_vals 内容用 空格 分割为一个数组
                res.data.forEach(item=>{
                    item.attr_vals = item.attr_vals?item.attr_vals.split(' '):[]
                    // 添加 new tag 所需属性,用于限制作用域
                    item.inputVisible = false
                    item.inputValue = ''
                })
                if(this.activeName === 'many'){
                    this.manyTableData = res.data
                }else{
                    this.onlyTableData = res.data
                }
            }
            
        },
        // 关闭添加对话框
        addDialogClosed(){
            // 重置输入内容
            this.$refs.addFormRef.resetFields()
        },
        // 添加
        addParams(){
            this.$refs.addFormRef.validate(async valid=>{
                if(!valid) return
                const{data:res} = await this.$http.post(`categories/${this.cateId}/attributes`,{
                    attr_name: this.addFrom.attr_name,
                    attr_sel: this.activeName,
                })
                if(res.meta.status !== 201) return this.$message.error('添加失败')
                this.$message.success('添加成功')
                this.getParamsData()
            })
            this.addDialogVisible = false
        },
        // 修改参数
        async showEditDialog(attr_id){
            this.editDialogVisible = true
            const{data:res} = await this.$http.get(`categories/${this.cateId}/attributes/${attr_id}`,{params: {
                attr_sel: this.activeName,
            }})
            if(res.meta.status !== 200) return this.$message.error('参数获取失败')
            this.editFrom = res.data
        },
        editDialogClosed(){
            this.$refs.editFormRef.resetFields()
        },
        // 确定修改
        editParams(){
            this.$refs.editFormRef.validate(async valid=>{
                if(!valid) return 
                const{data:res} = await this.$http.put(`categories/${this.cateId}/attributes/${this.editFrom.attr_id}`,{
                    attr_name: this.editFrom.attr_name,
                    attr_sel: this.activeName
                })
                if(res.meta.status !== 200) return this.$message.error('修改失败')
                this.$message.success('修改成功')
                this.getParamsData()
                this.editDialogVisible = false
            })
        },
        // 删除参数
        deleteParams(attr_id){
            this.$confirm('此操作将永久删除该参数, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
            }).then(async()=>{
                const{data:res} = await this.$http.delete(`categories/${this.cateId}/attributes/${attr_id}`)
                if(res.meta.status !== 200) return this.$message.error('删除失败')
                this.$message.success('删除成功')
                this.getParamsData()
            }).catch(()=>{
                this.$message.info('已取消')
            })
        },
        // 确定加入tag
        async handleInputConfirm(item){
            // trim()去除首尾空格
            if(item.inputValue.trim().length === 0){
                item.inputValue = ''
                item.inputVisible = false
                return
            }
            // 输入不为空时
            item.attr_vals.push(item.inputValue.trim())
            // 添加完成后重置输入框内容
            item.inputValue = ''
            item.inputVisible = false
            // 提交修改
            const{data:res} = await this.$http.put(`categories/${this.cateId}/attributes/${item.attr_id}`,{
                attr_name: item.attr_name,
                attr_sel: item.attr_sel,
                attr_vals: item.attr_vals.join(' '),  // 用 空格 拼接为字符串
            })
            if(res.meta.status !== 200) return this.$message.error('添加失败')
            this.$message.success('添加成功')
        },
        // button 与 input 显示转换
        showInput(item){
            item.inputVisible = true
            this.$nextTick(() => {
                this.$refs.saveTagInput.$refs.input.focus();
            })
        },
        async handleClose(i,item){
            item.attr_vals.splice(i,1)
            // 提交删除
            const{data:res} = await this.$http.put(`categories/${this.cateId}/attributes/${item.attr_id}`,{
                attr_name: item.attr_name,
                attr_sel: item.attr_sel,
                attr_vals: item.attr_vals.join(' '),  // 用 空格 拼接为字符串
            })
            if(res.meta.status !== 200) return this.$message.error('删除失败')
            this.$message.success('删除成功')
        }
    },
    computed: {
        // 判断按钮是否禁用
        isBtnDisabled(){
            if(this.selectedKeys.length !== 3){
                return true
            }else{
                return false
            }
        },
        // 选中的三级分类id
        cateId(){
            if(this.selectedKeys.length === 3){
                return this.selectedKeys[this.selectedKeys.length-1]
            }else{
                return undefined
            }
        },
        diaTitle(){
            if(this.activeName === 'many'){
                return '动态参数'
            }else{
                return '静态属性'
            }
        }
    }
}
</script>

<style lang="less" scoped>
.button-new-tag{
    margin-left: 20px;
}
.input-new-tag{
    width: 120px;
    margin-left: 20px;
}
</style>